package com.foreknow.elmboot.service.impl;

import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrderDetailetMapper;
import com.foreknow.elmboot.mapper.OrdersMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.OrderDetailet;
import com.foreknow.elmboot.po.Orders;
import com.foreknow.elmboot.service.OrdersService;
import com.foreknow.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderDetailetMapper orderDetailetMapper;
    @Override
    public int sinsert(Orders orders) {
        Cart cart = new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());
        //查询购物车
        List<Cart> list = cartMapper.query(cart);
        //创建订单,并返回orderId
        String date = CommonUtil.getCurrentDate();
        orders.setOrderDate(date);
        ordersMapper.insert(orders);
        int a = orders.getOrderId();
        //批量添加订单明细
        List<OrderDetailet> detailets = new ArrayList<>();
        for (Cart lc:list) {
            OrderDetailet orderDetailet = new OrderDetailet();
            orderDetailet.setOrderId(a);
            orderDetailet.setFoodId(lc.getFoodId());
            orderDetailet.setQuantity(lc.getQuantity());
            detailets.add(orderDetailet);
        }
        orderDetailetMapper.save(detailets);
        //删除购物车
        for (Cart lt:list) {
            Cart cart1 = new Cart();
            cart1.setUserId(orders.getUserId());
            cart1.setBusinessId(orders.getBusinessId());
            cart1.setFoodId(lt.getFoodId());
            cartMapper.delete(cart1);
        }
        return a;
    }

    @Override
    public Orders squeryobo(Integer orderId) {
//        Orders orders = new Orders();
//        orders = ordersMapper.queryobo(orderId);
//        List<OrderDetailet> list = orderDetailetMapper.query(orderId);
//        orders.setList(list);
//        return orders;
        return ordersMapper.queryobo(orderId);
    }

    @Override
    public List<Orders> squeryall(String userId) {
//        List<Orders> list = ordersMapper.queryall(userId);
//        for (Orders oo:list) {
//            List<OrderDetailet> li = orderDetailetMapper.query(oo.getOrderId());
//            oo.setList(li);
//        }
//        return list;
        return ordersMapper.queryall(userId);
    }

    @Override
    public int pay(Integer orderId) {
        return ordersMapper.pay(orderId);
    }
}
